package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.common.admin.dtos.AdUserDTO;
import com.heima.model.common.admin.pojos.AdUser;
import com.heima.model.common.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!inputPwd.equals(user.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        if (user.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        user.setLoginTime(new Date());
        this.updateById(user);
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user,userVO);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",userVO);
        return ResponseResult.okResult(map);
    }
}
